/**
 * API服务模块，用于处理与AI服务的通信
 */

class AIService {
  /**
   * 构造函数
   * @param {string} apiKey - API密钥
   * @param {string} serviceProvider - AI服务提供商 ('openai', 'anthropic', 'gemini', etc.)
   */
  constructor(apiKey, serviceProvider = 'openai') {
    this.apiKey = apiKey;
    this.serviceProvider = serviceProvider;
  }

  /**
   * 调用AI API处理文本
   * @param {string} prompt - 提示词
   * @param {Object} options - 选项参数
   * @returns {Promise<string>} 处理结果
   */
  async processText(prompt, options = {}) {
    // 验证参数
    if (!prompt || typeof prompt !== 'string') {
      throw new Error('提示词不能为空且必须是字符串');
    }
    
    if (!this.apiKey || typeof this.apiKey !== 'string') {
      throw new Error('API密钥不能为空且必须是字符串');
    }
    
    // 根据服务提供商调用相应的API
    switch (this.serviceProvider) {
      case 'openai':
        return this._callOpenAI(prompt, options);
      case 'anthropic':
        return this._callAnthropic(prompt, options);
      case 'gemini':
        return this._callGemini(prompt, options);
      default:
        throw new Error(`不支持的AI服务提供商: ${this.serviceProvider}`);
    }
  }

  /**
   * 调用OpenAI API
   * @param {string} prompt - 提示词
   * @param {Object} options - 选项参数
   * @returns {Promise<string>} 处理结果
   */
  async _callOpenAI(prompt, options) {
    const model = options.model || 'gpt-3.5-turbo';
    const temperature = options.temperature || 0.7;
    
    // 验证参数
    if (temperature < 0 || temperature > 2) {
      throw new Error('温度参数必须在0到2之间');
    }
    
    try {
      const response = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.apiKey}`
        },
        body: JSON.stringify({
          model: model,
          messages: [{role: 'user', content: prompt}],
          temperature: temperature
        })
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`OpenAI API请求失败: ${response.status} ${response.statusText} - ${errorText}`);
      }

      const data = await response.json();
      if (!data.choices || !data.choices[0] || !data.choices[0].message || !data.choices[0].message.content) {
        throw new Error('OpenAI API返回的数据格式不正确');
      }
      
      return data.choices[0].message.content;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 调用Anthropic API
   * @param {string} prompt - 提示词
   * @param {Object} options - 选项参数
   * @returns {Promise<string>} 处理结果
   */
  async _callAnthropic(prompt, options) {
    const model = options.model || 'claude-3-haiku-20240307';
    const temperature = options.temperature || 0.7;
    const maxTokens = options.maxTokens || 1024;
    
    // 验证参数
    if (temperature < 0 || temperature > 1) {
      throw new Error('温度参数必须在0到1之间');
    }
    
    if (maxTokens <= 0 || maxTokens > 4096) {
      throw new Error('最大令牌数必须在1到4096之间');
    }
    
    try {
      const response = await fetch('https://api.anthropic.com/v1/messages', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-api-key': this.apiKey,
          'anthropic-version': '2023-06-01'
        },
        body: JSON.stringify({
          model: model,
          max_tokens: maxTokens,
          temperature: temperature,
          messages: [{role: 'user', content: prompt}]
        })
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`Anthropic API请求失败: ${response.status} ${response.statusText} - ${errorText}`);
      }

      const data = await response.json();
      if (!data.content || !data.content[0] || !data.content[0].text) {
        throw new Error('Anthropic API返回的数据格式不正确');
      }
      
      return data.content[0].text;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 调用Google Gemini API
   * @param {string} prompt - 提示词
   * @param {Object} options - 选项参数
   * @returns {Promise<string>} 处理结果
   */
  async _callGemini(prompt, options) {
    const model = options.model || 'gemini-pro';
    const temperature = options.temperature || 0.7;
    
    // 验证参数
    if (temperature < 0 || temperature > 2) {
      throw new Error('温度参数必须在0到2之间');
    }
    
    try {
      const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${this.apiKey}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          contents: [{
            parts: [{
              text: prompt
            }]
          }],
          generationConfig: {
            temperature: temperature
          }
        })
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`Gemini API请求失败: ${response.status} ${response.statusText} - ${errorText}`);
      }

      const data = await response.json();
      if (!data.candidates || !data.candidates[0] || !data.candidates[0].content || 
          !data.candidates[0].content.parts || !data.candidates[0].content.parts[0] || 
          !data.candidates[0].content.parts[0].text) {
        throw new Error('Gemini API返回的数据格式不正确: ' + JSON.stringify(data));
      }
      
      return data.candidates[0].content.parts[0].text;
    } catch (error) {
      throw error;
    }
  }
}

// 导出AIService类
if (typeof module !== 'undefined' && module.exports) {
  module.exports = AIService;
} else {
  window.AIService = AIService;
}